<?php

namespace common\service;

use common\model\TenantAuthenticationModel;
use common\model\TenantGroupMemberModel;
use common\model\TenantGroupModel;
use common\model\TenantModel;
use common\model\TenantStepCategoryLevelModel;
use common\model\TenantUserModel;
use support\ErrorCode;
use teamones\Request;
use Webman\Stomp\Client;

class TenantGroupMemberService
{

    protected $tenantGroupMemberModel;

    public function __construct()
    {
        $this->tenantGroupMemberModel = model(TenantGroupMemberModel::class);
    }

    /**
     * 查找公司列表
     * @param $param
     * @return array|void
     * @throws \Exception
     */
    public function select($param)
    {
        $options = $param['param'];
        $tenantStepCateGoryLevelData = [];
        $tenantGroupMemberData = $this->tenantGroupMemberModel->where($options['filter'])->page(...$options['page'])->select();
        $tenantGroupData = model(TenantGroupModel::class)->find($options['filter']['tenant_group_id']);
        if (empty($tenantGroupMemberData)) {
            return [];
        }
        $tenantIds = array_column($tenantGroupMemberData, 'tenant_id');
        $tenantModel = model(TenantModel::class);
        $tenantOptions = [
            "fields" => 'tenant.id,tenant.name,tenant.status,tenant.created',
            'filter' => [
                'tenant.id' => ['IN', implode(',', $tenantIds)],
                'tenant.status' => 'active'
            ],
        ];
        $tenantList = $tenantModel->selectData($tenantOptions);
        if (empty($tenantList)) {
            throw_strack_exception('Tenant Not Found', ErrorCode::TENANT_NOT_EXIST);
        }
        // 每个公司对应不同分类的等级数据
        $tenantStepCateGoryLevelModel = model(TenantStepCategoryLevelModel::class);
        $tenantStepCateGoryLevelList = $tenantStepCateGoryLevelModel
            ->field("uuid,created,updated,created_by", true)
            ->where(['tenant_id' => ['In', implode(',', $tenantIds)]])
            ->select();
        if (!empty($tenantStepCateGoryLevelList)) {
            $tenantStepCateGoryLevelData = array_group_by($tenantStepCateGoryLevelList, 'tenant_id');
        }
        // 获取公司认证信息
        $tenantAuthenticationModel = model(TenantAuthenticationModel::class);
        $tenantAuthenticationList = $tenantAuthenticationModel->where(['tenant_id' => ['In', implode(',', $tenantIds)]])->select();
        $tenantAuthenticationMap = array_column($tenantAuthenticationList, null, 'tenant_id');
        $tenantData = [];
        $ownerOrder = [];
        //应当只筛选 集团类型的订单
        $tenantOrder = Request::connection()
            ->setHeader([
                'X-Userinfo' => request()->getXUserInfo(),
            ])
            ->setServerHost('teamones-saas')
            ->setRoute('order/get_tenant_group_order')
            ->setBody([
                'param' => [
                    'filter' => [
                        'tenant_group_id' => $options['filter']['tenant_group_id'],
                        "type" => "tenant_group",
                        'status' => ['-in', 'inprogress,wait_for_add_settlement,wait_for_review_settlement,wait_for_settlement,done'],
                        [
                            'from_tenant_id' => ['-in', implode(',', $tenantIds)],
                            'to_tenant_id' => ['-in', implode(',', $tenantIds)],
                            '_logic' => '-or'
                        ]
                    ]
                ]
            ])
            ->setMethod('POST')
            ->request()['data'];

        $fromTenantIds = array_column($tenantOrder, 'from_tenant_id');
        $toTenantIds = array_column($tenantOrder, 'to_tenant_id');
        foreach ($tenantList['rows'] as $item) {
            $item['tenant']['level_data'] = $tenantStepCateGoryLevelData[$item['tenant']['id']] ?? [];
            $item['tenant']['legal_person_name'] = $tenantAuthenticationMap[$item['tenant']['id']]['legal_person_name'] ?? "";
            $item['tenant']['not_quit'] = in_array($item['tenant']['id'], $fromTenantIds) || in_array($item['tenant']['id'], $toTenantIds);
            $ownerOrder[] = $item['tenant']['is_owner'] = $tenantGroupData['tenant_id'] == $item['tenant']['id'];
            $tenantData[] = $item['tenant'];
        }
        array_multisort($ownerOrder, SORT_DESC, $tenantData);
        return $tenantData;

    }

    /**
     * 新增集团成员
     * @param $data
     * @return bool
     * @throws \Throwable
     */
    public function add($data)
    {
        $tenantGroupMemberData = $data;
        $tenantModel = model(TenantModel::class);
        $tenantData = $tenantModel->where(['id' => $data['tenant_id']])->find();
        if (empty($tenantData)) {
            throw_strack_exception('Tenant Not Found', ErrorCode::TENANT_NOT_EXIST);
        }
        if ($tenantData['status'] != 'active') {
            throw_strack_exception('Tenant Not Active', ErrorCode::TENANT_STATUS_ACTIVE);
        }
        $tenantAuth = model(TenantAuthenticationModel::class);
        $tenantAuthData = $tenantAuth->where(['tenant_id' => $data['tenant_id']])->find();
        if (empty($tenantAuthData) || $tenantAuthData['status'] != "active") {
            throw_strack_exception('Tenant Not Auth', ErrorCode::TENANT_AUTHENTICATION_FAILED);
        }
        $tenantGroupModel = model(TenantGroupModel::class);
        $tenantGroupExists = $tenantGroupModel->find($data['tenant_group_id']);
        if (empty($tenantGroupExists)) {
            throw_strack_exception('TenantGroup Not Exists', ErrorCode::TENANT_GROUP_NOT_EXIST);
        }
        $tenantGroupMemberExists = $this->tenantGroupMemberModel->where($data)->find();
        if ($tenantGroupMemberExists) {
            throw_strack_exception('Member Already Exists', ErrorCode::TENANT_MEMBER_EXISTS);
        }
        $resTenantGroupMemberData = $this->tenantGroupMemberModel->addItem($tenantGroupMemberData);

        // 新增公司与公司之间有外部供应商的关系
        if (!empty($resTenantGroupMemberData)) {
            $resTenantGroupMemberData["user_id"] = \request()->getUserId();
            Client::send('add_tenant_group_supplier', build_queue_data_with_xu($resTenantGroupMemberData));
        }

        return $resTenantGroupMemberData;
    }

    /**
     * 退出集团
     * @param $data
     * @param $tenantId
     * @return false|float|int|mixed|string
     */
    public function quit($data, $tenantId)
    {
        $quitTenantId = $data['data']['tenant_id'] ?? $tenantId;
        $tenantGroupId = $data['data']['tenant_group_id'];
        $tenantGroupModel = model(TenantGroupModel::class);
        $tenantGroupOwner = $tenantGroupModel->find($tenantGroupId);
        // 必须是集团拥有者才能踢出成员
        if (isset($data['data']['tenant_id'])) {
            if ($tenantGroupOwner['tenant_id'] != $tenantId) {
                throw_strack_exception('Tenant Not Permission', ErrorCode::TENANT_NOT_PERMISSION);
            }
        }
        // 如果集团拥有者是当前需要退出的公司，就需要先转让才能退出
        if ($tenantGroupOwner['tenant_id'] == $quitTenantId) {
            throw_strack_exception('Group owner cannot quit', ErrorCode::TENANT_GROUP_OWNER_EXISTS);
        }
        //应当只筛选 集团类型的订单
        $tenantOrder = Request::connection()
            ->setHeader([
                'X-Userinfo' => request()->getXUserInfo(),
            ])
            ->setServerHost('teamones-saas')
            ->setRoute('order/find')
            ->setBody([
                'param' => [
                    'filter' => [
                        'tenant_group_id' => $tenantGroupId,
                        "type" => "tenant_group",
                        'status' => ['-in', 'inprogress,wait_for_add_settlement,wait_for_review_settlement,wait_for_settlement,done'],
                        [
                            'from_tenant_id' => $quitTenantId,
                            'to_tenant_id' => $quitTenantId,
                            '_logic' => '-or'
                        ]
                    ]
                ]
            ])
            ->setMethod('POST')
            ->request()['data'];
        if (!empty($tenantOrder)) {
            throw_strack_exception('The tenant still has tasks that cannot be removed', ErrorCode::TENANT_TASK_UNDONE);
        }
        $tenantMemberFilter = [
            'tenant_id' => $quitTenantId,
            'tenant_group_id' => $data['data']['tenant_group_id']
        ];
        $tenantMemberData = $this->tenantGroupMemberModel->where($tenantMemberFilter)->find();
        if (empty($tenantMemberData)) {
            throw_strack_exception('The tenant already not exists', ErrorCode::TENANT_MEMBER_NOT_EXISTS);
        }
        return $this->tenantGroupMemberModel->delete($tenantMemberData['id']);
    }

    /**
     * 获取集团下的供应商
     * @param $param
     * @return array
     */
    public function selectTenantGroupMemberSupplier($param)
    {
        $filter = $param["filter"];
        $tenantId = $filter["tenant_id"];
        $page = $param["page"] ?? [1, C("database.database_max_select_rows")];
        if (empty($filter["tenant_group_id"])) {
            $tenantGroupIds = model(TenantGroupMemberModel::class)->where(["tenant_id" => $tenantId])->column("tenant_group_id");
            if (empty($tenantGroupIds)) {
                return [];
            }
            $tenantGroupMemberFilter = [
                "tenant_group_member.tenant_group_id" => ["IN", $tenantGroupIds],
                "tenant_group_member.tenant_id" => ["NEQ", $tenantId],
            ];

        } else {
            $tenantGroupMemberFilter = [
                "tenant_group_member.tenant_group_id" => $filter["tenant_group_id"],
                "tenant_group_member.tenant_id" => ["NEQ", $tenantId],
            ];
        }


        $tenantGroupMemberList = model(TenantGroupMemberModel::class)
            ->where($tenantGroupMemberFilter)
            ->page(...$page)
            ->field("tenant_id")
            ->group("tenant_id")
            ->select();

        if (empty($tenantGroupMemberList)) {
            return [];
        }

        //获取供应商详细信息
        $tenantGroupMemberTenantIds = array_column($tenantGroupMemberList, 'tenant_id');
        $supplierFilter = [
            "supplier.type" => "outside",
            "supplier.tenant_id" => $tenantId,
            "supplier.from_tenant_id" => ["IN", $tenantGroupMemberTenantIds],
            'tenant_authentication.status' => "active",
            'tenant_authentication.fdd_cert_status' => "1",
            'tenant_authentication.fdd_auth_status' => "4"
        ];

        $supplierService = new SupplierService();
        if (isset($filter["step_category_id"])) {
            $supplierFilter["supplier.step_category_ids"] = $filter["step_category_id"];
        }

        $param = [
            "param" => [
                "filter" => $supplierFilter
            ]
        ];
        $supplierList = $supplierService->select($param["param"], $param["param"]["filter"]);


        //更改类型
        if (empty($supplierList)) {
            return [];
        }


        $supplierList["rows"] = array_map(function ($supplierItem) {
            $supplierItem["type"] = "tenant_group";
            return $supplierItem;
        }, $supplierList["rows"]);
        return $supplierList;
    }

    /**
     * 获取当前租户的集团
     * @param $param
     * @return array|false|mixed|string
     */
    public function getTenantGroup($param)
    {
        $page = $param["page"] ?? [1, C("database.database_max_select_rows")];
        $fields = $param["fields"] ?? "*";
        $tenantGroupList = model(TenantGroupModel::class)->join("tenant_group_member on tenant_group_member.tenant_group_id = tenant_group.id")
            ->where($param["filter"])->page(...$page)
            ->field("tenant_group.id")
            ->group("tenant_group.id")
            ->select();

        if (empty($tenantGroupList)) {
            return [];
        }
        $tenantGroupList = array_column($tenantGroupList, "id");

        return model(TenantGroupModel::class)->where(["id" => ["IN", $tenantGroupList]])->field($fields)->select();
    }

    /**
     * 根据项目获取集团成员
     * @param $param
     * @return array
     */
    public function getTenantGroupMemberByProject($param)
    {
        $res = [
            'tenant_group_member_ids' => [],
            'tenant_step_category' => [],
            'step_category_ids' => '',
            'tenant_address' => [],
        ];
        // 先获取项目所属租户在的集团ID
        $tenantGroupIds = model(TenantGroupMemberModel::class)->where(['tenant_id' => $param['filter']['project_tenant_id']])->column("tenant_group_id");
        if (empty($tenantGroupIds)) {
            return $res;
        }
        $filter = [
            'tenant_group_id' => ['IN', $tenantGroupIds]
        ];
        // 最后获取在同一个集团下的租户
        $allTenantIds = $param['filter']['all_project_tenant_id'] ?? [];
        if (!empty($allTenantIds)) {
            $filter['tenant_id'] = ['IN', $allTenantIds];
        }
        $res['tenant_group_member_ids'] = model(TenantGroupMemberModel::class)->where($filter)->group("tenant_id")->column("tenant_id");
        $isSelectTenantStepCategory = $param['filter']['options']['select_tenant_step_category'] ?? 'no';
        if ($isSelectTenantStepCategory == 'yes') {
            // 查找所有租户所涉及到的工序分类，不区分是否为集团内部成员
            $tenantStepCategoryList = model(TenantStepCategoryLevelModel::class)->field('tenant_id,step_category_id')->where(['tenant_id' => ['IN', $allTenantIds]])->select();
            $tenantStepCategoryList = array_group_by($tenantStepCategoryList, 'tenant_id');
            $stepCategoryIds = [];
            foreach ($tenantStepCategoryList as &$item) {
                $item = array_column($item, 'step_category_id');
                $stepCategoryIds = array_merge($item, $stepCategoryIds);
            }
            $res['tenant_step_category'] = $tenantStepCategoryList;
            $res['step_category_ids'] = join(',', array_unique($stepCategoryIds));
        }
        // 查找所有租户的地理位置
        $isSelectTenantAddress = $param['filter']['options']['select_tenant_address'] ?? 'no';
        if ($isSelectTenantAddress == 'yes') {
            $authFields = 'id,tenant_id,company_name,company_office_address,province,cities,coordinate,city_coordinate';
            $tenantAddressList = model(TenantAuthenticationModel::class)->field($authFields)->where(['tenant_id' => ['IN', $allTenantIds]])->select();
            $res['tenant_address'] = array_column($tenantAddressList, null, 'tenant_id');
        }
        return $res;
    }

    /**
     * 获取集团列表
     * @param $param
     * @return array
     * @throws \Exception
     */
    public function list($param)
    {
        return model(TenantGroupMemberModel::class)->selectData($param);
    }
}
